﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace WebDummy
{
    class Logindetails : Fetch
    {
        public Logindetails(String Webpage) : base (Webpage)
        {

        }

        

        public void login(String User,String Password,String LoginPage)
        {
            StringBuilder Params = new StringBuilder();
            Regex TypeReg = new Regex("(?<=type=\")[A-Za-z0-9]+(?=\")");
            Regex NameReg = new Regex("(?<=name=\")[A-Za-z0-9]+(?=\")");
            Regex ValueReg = new Regex("(?<=value=\")[A-Za-z0-9]+(?=\")");
            foreach (String Param in getParameters())
            {
                //var test = Re.getElementById("derp");
                String Type = TypeReg.Match(Param).Value;
                String Name = NameReg.Match(Param).Value;
                String Value = ValueReg.Match(Param).Value;
                if (Type.Equals("text"))
                {
                    if (Name.Equals("name"))
                        Params.Append(Name + "=" + User + "&");
                   
                }
                else if (Type.Equals("password"))
                    Params.Append(Name + "=" + Password + "&");
                else if (Type.Equals("checkbox"))
                    Params.Append(Name + "=1&");
                else if (Type.Equals("hidden"))
                    Params.Append(Name + "=" + Value + "&");
                else if (Type.Equals("submit"))
                    Params.Append(Name + "=" + Value + "&");

                
            }
            Params.Remove(Params.ToString().LastIndexOf("&"), 1);
            PostData( Params.ToString(),LoginPage);
        }

        private string getLoginForm()
        {

            Regex FormPat = new Regex("<form name=\\\"login\\\" method=\\\"POST\\\" action=\\\"[A-Za-z0-9]+.php\\\">[A-Za-z0-9<>\\s=\"-\\/:;]+</form>");
            Match Form = FormPat.Match(Response);

            return Form.Value;
        }
        private List<String> getParameters()
        {
            Regex FormPat = new Regex("<input type=\\\"[A-Za-z]+\\\" [\\sA-Za-z0-9=\\\"]+ />");
            Regex ButtonPat = new Regex("<button[A-Za-z0-9 \\\"\\s =:;\\.+]* type=\\\"submit\\\" [A-Za-z0-9 \\\"\\s =:;\\.+\']*>");
            MatchCollection Form = FormPat.Matches(Response);
            List<String> Parameters = new List<String>();

            foreach (Match Param in Form)
            {
                Parameters.Add(Param.Value);
            }
            Parameters.Add(ButtonPat.Match(Response).Value);
            return Parameters;
        }
    }
}
